package com.itheima.web.controller;

import com.itheima.pojo.User;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

/**
 * @author huyoufu <https://github.com/huyoufu>
 * @TIME 2020-08-11 09:37
 * @description
 * 演示参数绑定的例子
 */


@Controller
@RequestMapping("/user05")
public class demo5_参数绑定 {

    @RequestMapping("/login.do")
    public String login(Model model, HttpServletRequest request) throws ServletException, IOException {
        System.out.println("用户登录...");

        //获取用户名  获取密码
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        System.out.println("获取用户名:"+username);
        System.out.println("获取用密码:"+password);

        //调用service  查询用户.......

        model.addAttribute("info","模拟的登录数据");

        return "user/success";
    }

    @RequestMapping("/register.do")
    public String register(Model model,HttpServletRequest request) throws ServletException, IOException {
        System.out.println("用户注册...");

        //获取所有参数
        Map<String, String[]> parameterMap = request.getParameterMap();

        //封装对象
        User user = new User();


        /*
            BeanUtils对象

            populate(Object bean, Map<String,String[]>properties)  将Map数据封装到指定Javabean中，一般用于将表单的所有数据封装到javabean

            setProperty(Object obj,String name,Object value) 设置属性值

            getProperty(Object obj,String name) 获得属性值
        */
        try {
            BeanUtils.populate(user,parameterMap);
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("封装完的结果:"+user);

        //调用service 保存用户....

        model.addAttribute("info","模拟的注册数据");

        return "user/success";

    }

    @RequestMapping("/logout.do")
    public String logout(Model model) throws ServletException, IOException {
        System.out.println("退出登录...");

        model.addAttribute("info","模拟的推出登录数据");

        return "user/success";

    }
}
